package com.kate.mall.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
    @ResponseBody
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseEntity exceptionHandler(Exception e) {
        log.error("执行异常", e);
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e1 = (MethodArgumentNotValidException) e;
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(e1.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof NDException) {
            NDException exception = (NDException) e;
            return ResponseEntity.status(((NDException) e).geterrno())
                    .body(((NDException) e).getMsg());
        } else if (e instanceof BindException) {
            BindException e1 = (BindException) e;
            log.warn("throw BindingException,{}", e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(e1.getBindingResult().getFieldError().getDefaultMessage());
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("后端请求失败");
        }
    }
}